﻿using System;
using System.Collections.Generic;
using System.Data.Common;

using Utilities;

namespace DataAccess
{
    /// <summary>
    /// Maps the value returned by the reader to a type
    /// </summary>
    public class TypeMap
    {
        private int _index;

        private IDictionary<int, Type> _map = new Dictionary<int, Type>();

        #region Fluent methods

        public static TypeMap Map()
        {
            return new TypeMap();
        }

        public TypeMap Index(int index)
        {
            _index = index;

            return this;
        }

        public TypeMap Type(int index, Type type)
        {
            _map.Add(index, type);

            return this;
        }
        
        #endregion

        #region Methods

        internal object CreateObject(DbDataReader reader)
        {
            int value = reader.GetInt32(_index); // Read the value from the reader
            Type type = _map[value]; // Retrieve the type

            return type.CreateInstance(); // Create an instance from the type
        } 

        #endregion
    }
}
